#!/usr/bin/env python
#coding:utf-8
import urllib2,re

class Stock:
    """Class to get up-to-date information for your stock"""

    def __init__( self, stockId="sh000001"):
        """initializing the stock and the url received"""  
        self.setStockId(stockId)
        self.setUrl(stockId)


    def setStockId( self, stockId):
        """function to set the ID of stock"""    
        self.__stockId=stockId


    def setUrl(self, stockId):
        """function to set the requesting url"""
        self.__url='http://hq.sinajs.cn/list=s_%s'%stockId


    def getStockId (self , stockId):
        """function to return the ID of stock"""    
        return self.__stockId


    def getPage( self ):
        """function to get the content of the web page.return the string page content"""
        url=self.__url
        try:
            page = urllib2.urlopen(url)
            page_content = page.read()
            page.close()
        except:
            return ""
        return page_content


    def getStock( self ):
        """function to get the info of the stock.Return a string respon."""
        page_content=self.getPage() # Get the content of the result web page from SINA stock 
        regex=r'var hq_str_s_'+self.__stockId+'=\"(.*)\"\;' # a sign to find the info from the content 
        match=re.findall(regex,page_content) # Get the stock info from the pages
        info=["股票:","当前点数:","涨跌:","涨跌率(%):","成交量(手):","成交额(万):"]
        if(match==[""]):
            return ["Oops,你查询的股票不存在或输入格式有误，请检查下或输入'股票'获取帮助"]
        
        stock=match[0].split(",")
        count=0
        respon=""
        for i in stock:
            if i<>None:
                i=i.decode('gbk').encode("utf-8")
                respon=respon+info[count]+i+"  "
                count+=1

        return [respon]               
        